package msg;

import java.io.IOException;
import java.sql.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import page.PageState;
import usr.Usr;

public class SendMsg extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		HttpSession session = req.getSession();
		
		Usr from = (Usr) session.getAttribute("usr");
		if ( from == null ) {
			req.setAttribute("error_cause", PageState.LOGIN_NOT_EXIST);
			req.getRequestDispatcher("login.jsp").forward(req, resp);
		}
		
		boolean isBoardcast = new String("yes").equals(req.getParameter("is_boardcast"));
		
		int i = PageState.SUCCESSFUL;
		
		Usr to = new Usr();
		if ( !isBoardcast ) {
			to.setLogin(req.getParameter("to"));
			i = to.getUsrByLogin();
		}
		
		if ( i != PageState.SUCCESSFUL ) {
			req.setAttribute("error_cause", i);
//			System.out.println(i);
			req.getRequestDispatcher("sendMsg.jsp").forward(req, resp);
				
		} else {
			
			Msg msg = new Msg();
			msg.setDt(new Date(new java.util.Date().getTime()));
			msg.setTitle(req.getParameter("title"));
			msg.setContent(req.getParameter("content"));
			msg.setTo_id(to.getId());
			msg.setFrom_id(from.getId());
			msg.setBoardcast(isBoardcast);
			msg.sendMsg();
			req.getRequestDispatcher("msgs.jsp").forward(req, resp);
		}
	}
}
